﻿var grid, wnd, detailsTemplate, sourceGrid;
var mnggridid;
var contractpermistion, rowcommand
var MaHD=0;

$(document).ready(function () {

    //permisstion
    rowcommand = new Array();

    if (contractpermistion >= 7) {
        rowcommand.push({ name: "Delete", text: "Xóa", click: Delete });
        rowcommand.push({ name: "Groups", text: "Groups", click: AddGroups });
    }
    else {
        if (contractpermistion >= 3) {
            //co quyen xem danh sach hop dong
            // rowcommand.push({ name: "Groups", text: "Chi tiết", click: AddGroups });
        } else {
            //ko co quyen xem
            return;
        }
    }

    //end permisstion

    sourceGrid = {
        serverSorting: true,
        serverPaging: true,
        serverFiltering: true,
        batch: true,
        pageSize: 20,
        schema: {
            data: function (data) {
                if (data.d != null)
                    return data.d.lst;
                else
                    return [];
            },
            total: function (data) {
                return data.d.total;
            },
            model: {
                id: "ID",
                fields: {
                    UserName: { validation: { required: true} },
                    PassWord: { validation: { required: true} },
                    FullName: { validation: { required: false} },
                    Email: { validation: { required: false} }
                }
            }
        },
        transport: {
            read: {
                url: "/WS/UserService.aspx/GetListUser",
                contentType: "application/json; charset=utf-8",
                type: "POST"
            },
            update: {
                url: "/WS/UserService.aspx/UpdateUser",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                complete: function (e) {
                    if (e.responseText != "") {
                        var rsp =JSON.parse(JSON.stringify(eval('(' + e.responseText + ')')));
                        showMessage('error', rsp.d);
                    } else {
                        showMessage('success', "Cập nhật thành công");
                    }
                    $("#" + mnggridid).data("kendoGrid").dataSource.read();
                },
                error: function (e) {
                    alert('error');
                }
            },
            destroy: {
                url: "/WS/UserService.aspx/DeleteUser",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                complete: function (e) {
                    var msg = e.responseText.toString();
                    if (msg.indexOf("failed") != -1) {
                        showMessage('error', "Không thể xóa User này!");
                    }
                    else
                        showMessage('success', "Cập nhật thành công");
                    $("#" + mnggridid).data("kendoGrid").dataSource.read(); //refresh grid
                },
                error: function (e) {
                    alert('error');
                }
            },
            create: {
                url: "/WS/UserService.aspx/CreateUsers",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                complete: function (e) {
                    showMessage('success', "Cập nhật thành công");
                    $("#" + mnggridid).data("kendoGrid").dataSource.read();
                },
                error: function (e) {
                    alert('error');
                }
            },
            parameterMap: function (data, operation) {
                console.log(data);
                if (operation != "read") {
                    console.log(data);
                    if (operation == "create") {
                        return JSON.stringify({ obj: data.models, ParentID: MaHD })
                    }
                    return JSON.stringify({ obj: data.models })
                }
                else {
                    var keyword = $("#txtAdress").val();
                    data = $.extend({ Keyword: keyword, ParentID: MaHD }, data);
                    return JSON.stringify({ obj: data });
                }
            }
        }
    };


    grid = $("#" + mnggridid).kendoGrid({
        dataSource: sourceGrid,
        //height: 410,   

        toolbar: kendo.template($("#contractmngtemplate").html()),
        // toolbar: ["create", "save", "cancel"],
        pageable: true,
        resizable: true,
        //batch: true,
        navigatable: true,
        dataBound: onDataBound,
        columns: [
                                {
                                    field: "UserName", title: "UserName", width: "100px"
                                },
                                 {
                                     field: "PassWord", title: "PassWord", width: "120px"
                                 },
                                 {
                                     field: "FullName", title: "Họ và tên", width: "200px"
                                 },
                                {
                                    field: "Email", title: "Email"
                                },
                                {
                                    field: "DateCreated", title: "Ngày tạo"
                                },
                                { command: rowcommand,
                                    title: " ",
                                    width: (rowcommand.length * 65) + "px"
                                }
                            ],
        editable: (contractpermistion >= 7)
    });


});


//function Search() {
//    $('#' + mnggridid).data('kendoGrid').dataSource.read();
//}

function AddGroups(e) {
    var window = $("#window");
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    window.kendoWindow({width: "615px", title: "Nhóm người dùng", content: "/Account/UserGroups.aspx?UserID=" + dataItem.ID, modal: true, center:true, animation: false});
    window.data("kendoWindow").open().center();
    //console.log(dataItem);
    //window.location.href = "/Account/UserGroups.aspx?UserID=" + dataItem.ID;
}

function Delete(e) {
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var mahddelete = dataItem.ID;
    if (confirm("Bạn có chắc chắn muốn xóa User này không?")) {
        $.post("/Handlers/post.ashx", { ID: mahddelete, act: "xuser" }, function (result) {
            if (result == "success") {
                var grid = $('#' + mnggridid).data('kendoGrid');
                grid.dataSource.remove(dataItem);
                showMessage('success', "Xóa thành công!");
            } else {
                showMessage('error', "Không thể xóa tài khoản này!");
            }
        });
    }
}
function onDataBound(arg) {
//    var _grid = this;
//    _grid.tbody.find('>tr').each(function () {
//        var dataItem = _grid.dataItem(this);
//        if (!dataItem.IsMessageRead) {
//            $(this).addClass('someBoldClass');
//        }
//    })
}